package com.towexin.application.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.towexin.common.ResultData;
import com.towexin.config.mylogging.LogType;
import com.towexin.config.mylogging.MyLog;
import com.towexin.application.system.domain.FileUpload;
import com.towexin.application.system.service.FileUploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;

/**
 * TODO
 *
 * @author 唐伟鑫
 * @version 1.0
 * @date 2021/4/27 11:59
 */
@RestController
@RequestMapping("file")
public class FileUploadController {
    @Autowired
    private FileUploadService service;

    @RequestMapping("upload")
    public ResultData upload(MultipartFile file){
        String res = service.saveFile(file);
        return res==null?ResultData.NO():ResultData.OK(res);
    }

    @GetMapping("{id}")
    public void getFile(@PathVariable String id, HttpServletResponse response, HttpServletRequest request) throws Exception {
        service.getFile(id, response, request);
    }

    @GetMapping("img/{id}")
    public void getImageFile(@PathVariable String id, HttpServletResponse response, HttpServletRequest request) throws Exception {
        service.getImgFile(id, response, request);
    }

    @GetMapping("download/{id}")
    public void downloadFile(HttpServletResponse response, HttpServletRequest request, @PathVariable String id) throws Exception{
        service.downloadFile(id, response, request);
    }

    //@MyLog(type = 1, operation = "获取文件列表")
    @GetMapping("selectPage")
    public ResultData listFilesAndPage(int page, int limit){
        return ResultData.OK(service.page(new Page<>(page, limit), new QueryWrapper<FileUpload>().orderByAsc("created_time")));
    }

    @MyLog(type = LogType.DELETE, operation = "删除文件")
    @PostMapping("delete")
    public ResultData deleteFile(String[] ids){
        return service.deleteFile(Arrays.asList(ids))?ResultData.OK():ResultData.NO();
    }
}
